package com.lzx.reggie.controller

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.lzx.reggie.common.R
import com.lzx.reggie.entity.Employee
import com.lzx.reggie.service.EmployeeService
import org.apache.commons.lang.StringUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.util.DigestUtils
import org.springframework.web.bind.annotation.*
import javax.servlet.http.HttpServletRequest


@RestController
@RequestMapping("/employee")

class EmployeeController {

    companion object {
        private val log: Logger = LoggerFactory.getLogger(EmployeeController::class.java)

        /**
         * 用户初始密码：123456
         */
        private const val INITIAL_PASSWORD = "123456"
        private var INITIAL_PASSWORD_MD5 = DigestUtils.md5DigestAsHex(INITIAL_PASSWORD.toByteArray())
    }


    @Autowired
    private lateinit var employeeService: EmployeeService

    @PostMapping("/login")
    fun login(request: HttpServletRequest, @RequestBody employee: Employee): R<Any> {
        // 1、将页面提交的密码password进行md5加密处理
        val passwordByMd5 = DigestUtils.md5DigestAsHex(employee.password!!.toByteArray())


        // 如果没有查询到则返回登录失败结果
        val emp = employeeService.getOne(
            // 根据页面提交的用户名username构造条件
            KtQueryWrapper(Employee::class.java).apply {
                eq(Employee::username, employee.username)
            }) ?: return R.error("登录失败")

        // 4、密码比对，如果不一致则返回登录失败结果
        if (emp.password != passwordByMd5) {
            return R.error("登录失败")
        }
        // 5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.status == 0) {
            return R.error("账号禁用")
        }
        // 6、登录成功，将员工id存入Session并返回登录成功结果
        request.session.setAttribute("employee", emp.id)
        return R.success(emp)
    }

    @PostMapping("/logout")
    fun logout(request: HttpServletRequest): R<String> {
        request.session.removeAttribute("employee")
        return R.success("退出成功")
    }

    @PostMapping
    fun save(request: HttpServletRequest, @RequestBody employee: Employee): R<String> {
        log.info("新增员工，员工信息：$employee")

        //设置初始密码123456，需要进行md5加密处理
        employee.password = INITIAL_PASSWORD_MD5

        employeeService.save(employee)

        return R.success("新增员工成功")
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    fun page(page: Long, pageSize: Long, name: String?): R<Page<Employee>> {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name)

        //构造分页构造器
        val pageInfo = Page<Employee>(page, pageSize)

        //执行查询
        employeeService.page(pageInfo,
            // 构造条件构造器
            KtQueryWrapper(Employee::class.java).apply {
                // 添加过滤条件
                like(StringUtils.isNotEmpty(name), Employee::name, name)
                // 添加排序条件
                orderByDesc(Employee::updateTime)
            })
        return R.success(pageInfo)
    }

    /**
     * 根据id修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    fun update(request: HttpServletRequest, @RequestBody employee: Employee): R<String> {
        log.info(employee.toString())
        val id = Thread.currentThread().id
        log.info("线程id为：{}", id)
        employeeService.updateById(employee)
        return R.success("员工信息修改成功")
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    fun getById(@PathVariable id: Long): R<Any> {
        log.info("根据id查询员工信息...")
        val employee = employeeService.getById(id) ?: R.error("没有查询到对应员工信息")
        return R.success(employee)

    }
}